import router from './router'
import store from './store'
import {
  Message
} from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import {
  getToken
} from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import {
  getUserId
} from '@/utils/auth'
import {
  adminBuild
} from '@/api/user'

import Layout from '@/layout'
const _import = require('@/router/_import_development') // 获取组件的方法

NProgress.configure({
  showSpinner: false
}) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()
  // set page title
  document.title = getPageTitle(to.meta.title)
  // determine whether the user has logged in
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      next({
        path: '/'
      })
      NProgress.done()
    } else {
      try {
        adminBuild({
          platformUserId: getUserId()
        }).then(res => {
          //放行
          next()
          //为第一层包裹LAYOUT组件
          const data = res.data
          data.forEach((item, index, arr) => {
            if (item.children.length == 0) {
              let menu = {
                path: item.path,
                component: "#",
                children: [{
                  path: item.path,
                  component: item.component,
                  name: item.permissionName,
                  meta: item.meta
                }],
                name: item.permissionName,
              }
              arr[index] = menu
            }
          })
          const dynamicRouter = filterAsyncRouter(data)
          //动态添加路由
          router.addRoutes(dynamicRouter)
          NProgress.done()
        })
      } catch (error) {
        // remove token and go to login page to re-login
        await store.dispatch('user/resetToken')
        Message.error(error || 'Has Error')
        next(`/login?redirect=${to.path}`)
        NProgress.done()
      }
    }
  } else {
    /* has no token*/
    //console.log("没有token值")

    if (whiteList.indexOf(to.path) !== -1) {
      //console.log("^^^^^^^^^^^^^")
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})

//  遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap) {
  const accessedRouters = asyncRouterMap.filter(route => {
    if (route.component) {
      if (route.component === '#') {
        route.component = Layout
      } else {
        try {
          route.component = _import(route.component); // 导入组件
        } catch (error) {
          route.component = _import('/404') // 导入组件
          // Message.error('请查看控制台修改或者删除不存在的组件路径') //弹出异常('请修改或者删除不存在的组件路径')
        }
      }
    }
    if (route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    }
    return true
  })
  return accessedRouters
}
